package logic

import (
	"context"
	"errors"
	"shop-ease/internal/cache"
	"shop-ease/internal/mysql"

	"shop-ease/shopRpc/internal/svc"
	"shop-ease/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *shopRpc.CartAddRequest) (*shopRpc.CartAddResponse, error) {
	// 购物车添加
	if in.Quantity > 50 {
		return nil, errors.New("单词购买数量不得超过50件")
	}
	var products mysql.Product
	err := products.GetProductById(mysql.DB, in.ProductId)
	if err != nil {
		return nil, errors.New("该商品不存在")
	}

	if products.Stock < in.Quantity {
		return nil, errors.New("库存不足")
	}
	vStock := cache.GetStock(int(in.ProductId))
	if vStock < in.Quantity {
		return nil, errors.New("虚拟库存不足")
	}
	if cache.CartExists(int(in.ProductId)) {
		err = cache.CartUpdateQuantity(in.UserId, in.ProductId, in.Quantity)
		if err != nil {
			return nil, errors.New("购物车数量更新失败")
		}
		return &shopRpc.CartAddResponse{
			Success: true,
			Message: "购物车添加成功",
		}, nil
	}
	productMap := map[string]interface{}{
		"id":       products.ID,
		"name":     products.Name,
		"price":    products.Price,
		"img":      products.Img,
		"status":   products.Status,
		"quantity": in.Quantity,
	}

	if !cache.CartAdd(int(in.UserId), int(in.ProductId), productMap) {
		return nil, errors.New("购物车添加失败")
	}

	return &shopRpc.CartAddResponse{
		Success: true,
		Message: "购物车添加成功",
	}, nil
}
